package com.education.business.service.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.education.business.mapper.SystemRoleMapper;
import com.education.business.service.BaseService;
import com.education.common.model.PageInfo;
import com.education.common.util.ResultCode;
import com.education.model.RoleMenuDto;
import com.education.model.entity.SystemRole;
import com.education.model.entity.SystemRoleMenu;
import com.education.model.request.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 余一
 * @date 2021/9/25  12:33
 */
@Service
public class SystemRoleService extends BaseService<SystemRoleMapper, SystemRole> {

    @Autowired
    private SystemAdminRoleService systemAdminRoleService;
    @Autowired
    private SystemRoleMenuService systemRoleMenuService;

    public List<SystemRole> getRoleListByAdminId(Integer adminId) {
        return baseMapper.getRoleListByAdminId(adminId);
    }

    public PageInfo<SystemRole> listPage(PageParam pageParam, SystemRole systemRole) {
        LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(SystemRole.class)
                .like(ObjectUtils.isNotEmpty(systemRole.getName()),SystemRole :: getName,systemRole.getName());
            return selectPage(pageParam,queryWrapper);
    }

    @Transactional
    public ResultCode deleteById(Integer id) {
        if (systemAdminRoleService.checkRole(id)){
            return new ResultCode(ResultCode.FAIL,"角色已被使用");
        }
        this.removeById(id);
        systemRoleMenuService.deleteByRoleId(id);
        return new ResultCode(ResultCode.SUCCESS,"删除成功");
    }

    public void saveRolePermission(RoleMenuDto roleMenuDto) {
        Integer roleId = roleMenuDto.getRoleId();
        //先删除原有的角色权限
        systemRoleMenuService.deleteByRoleId(roleId);
        //再取出前端传递的dto里的menuIds
        List<Integer> menuIds = roleMenuDto.getMenuIds();
        //创建一个新容器，遍历menuIds，创建新的roleMenu对象装到容器中，
        List<SystemRoleMenu> systemRoleMenuList = new ArrayList<>();
        menuIds.forEach(menuId -> {
            SystemRoleMenu systemRoleMenu = new SystemRoleMenu();
            systemRoleMenu.setRoleId(roleId);
            systemRoleMenu.setMenuId(menuId);
            systemRoleMenuList.add(systemRoleMenu);
        });
        //批量添加角色菜单。
        systemRoleMenuService.saveBatch(systemRoleMenuList);
    }
}
